<template>
    <div class="cart">
        <van-checkbox v-model="allCheck">全选</van-checkbox>
        <van-swipe-cell v-for="item in cartList" :key="item.id">
            <van-checkbox v-model="item.checked"></van-checkbox>
            <van-card
                :price="item.price"
                :desc="item.detail"
                :title="item.title"
                :thumb="item.image"
            >
                <template #footer>
                    <van-stepper v-model="item.count" @change="cartCountChange($event, item.id)" />
                </template>
            </van-card>
            <template #right>
                <van-button
                    square
                    text="删除"
                    type="danger"
                    class="delete-button"
                    @click="delCart(item.id)"
                />
            </template>
        </van-swipe-cell>
        总价： {{ allPrice }}
    </div>
</template>

<script>
export default {
    data() {
        return {
            timer: null
        }
    },
    created() {
        const user_id = this.$store.state.user.userData.id;
        this.$store.dispatch('cart/GET_CART_LIST', { user_id })
    },
    computed: {
        cartList() {
            return this.$store.state.cart.cartList;
        },
        // 全选反选
        allCheck: {
            get() {
                return this.cartList.every(item => item.checked)
            },
            set(val) {
                this.cartList.forEach(item => item.checked = val)
            }
        },
        // 计算总价
        allPrice() {
            return this.cartList.reduce((a, b) => {
                return a + (b.checked ? (b.price * b.count) : 0)
            }, 0)
        }
    },
    methods: {
        cartCountChange(count, id) {
            // 防抖
            clearTimeout(this.timer)
            this.timer = setTimeout(() => {
                this.$store.dispatch('cart/SET_CART_COUNT', { count, id })
            }, 1000)
        },
        delCart(id) {
            this.$store.dispatch('cart/DEL_CART_BY_ID', id)


        }
    }
}
</script>

<style>
.goods-card {
    margin: 0;
    background-color: #fff;
}

.delete-button {
    height: 100%;
}
</style>